{% extends 'template/jhTemplateV4.html'%} {% block vueTemplate %}

<script id="app-template" type="text/html">
	<div>
	<v-app mobile-breakpoint="sm">
	  <jh-menu />
	  <v-main class="mt-15">
	    <!-- 头部内容 >>>>>>>>>>>>> -->
	    <div class="jh-page-second-bar px-8">
	      <v-row>
	        <v-col cols="12" xs="12" sm="12" md="4" xl="3">
	          <div class="pt-3 text-h7 font-weight-bold">合同管理
	            <!-- 帮助页按钮 -->
	            <v-icon @click="isHelpPageDrawerShown = true" color="success" small>mdi-help-circle-outline
	            </v-icon>
	          </div>
	          <v-breadcrumbs class="pb-3 pt-0 pl-0" :items="breadcrumbs" divider="-"></v-breadcrumbs>
	        </v-col>
	        <!-- 搜索条件表单 >>>>>>>> -->
	        <v-col cols="12" xs="12" sm="12" md="8" xl="9">
	          <v-row class="jh-backend-form-container justify-end ma-0 py-1 pb-xs-2">
	            <v-col cols="12" xs="6" sm="6" md="4" xl="3" class="pa-xs-0 pb-2 pl-1 pl-xs-1">
	              <v-select v-model="serverSearchInput.leaseType" color="success" prefix="租赁类型:" class="jh-v-input bg-white" :items="constantObj.leaseType" dense filled single-line></v-select>
	            </v-col>
	            <v-btn class="jh-backend-search-btn elevation-0 ml-0 mt-3" color="success" small @click="doUiAction('getTableData')">
	              查询
	            </v-btn>
	          </v-row>
	        </v-col>
	        <!-- <<<<<<<< 搜索条件表单 -->
	      </v-row>
	    </div>
	    <!-- <<<<<<<<<<<<< 头部内容 -->

	    <div class="jh-page-body-container px-8">
	      <!-- 页面内容 >>>>>>>>>>>>> -->
	      <v-card class="rounded-lg">
	        <v-row class="ma-0 pa-4">
	          <!-- 新增按钮 -->
	          <v-btn color="success" class="elevation-0 mr-2" @click="doUiAction('startCreateItem')" small>新增
	          </v-btn>
						<v-btn color="success" class="elevation-0 mr-2" @click="doUiAction('createCarRequest')" small>批量处理
	          </v-btn>
	          <v-spacer></v-spacer>
	          <!-- 搜索过滤 -->
	          <v-col cols="12" xs="8" sm="4" md="3" xl="2" class="pa-0">
	            <v-text-field color="success" v-model="searchInput" prefix="搜索：" class="jh-v-input" dense filled single-line></v-text-field>
	          </v-col>
	        </v-row>
	        <!-- 表格 -->
	        <v-data-table
	          :headers="headers"
	          :items="tableData"
	          :search="searchInput"
	          :footer-props="{ itemsPerPageOptions: [20, 50, -1], itemsPerPageText: '每页', itemsPerPageAllText: '所有'}"
	          :items-per-page="-1"
	          mobile-breakpoint="0"
	          :loading="isTableLoading"
	          checkbox-color="success"
	          :class="{'zebraLine': isTableZebraLineShown }"
	          fixed-header
	          class="jh-fixed-table-height elevation-0 mt-0 mb-xs-4"
						show-select item-key="contractId" @item-selected="tableItemSelected" v-model="tableSelected" @toggle-select-all="tableToggleSelectAll">
						<template v-slot:item.get-car-ticket="{item}">
							<template v-for="(ticketItem, ticketIndex) in item.getCarTicket">
								<div :key="ticketIndex">
									<span @click="doUiAction('updateCarRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2 pr-2">申请_{{ticketItem.ticketRequestAt | mdFormat}}</span>
									<span v-if="ticketItem.ticketStatus !== '申请'" @click="doUiAction('viewCarRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2">发车{{ticketItem.ticketStatus}}_{{ticketItem.ticketStatusAt | mdFormat}}</span>
								</div>
							</template>
						</template>
						<template v-slot:item.return-car-ticket="{item}">
							<template v-for="(ticketItem, ticketIndex) in item.returnCarTicket">
								<div :key="ticketIndex">
									<span @click="doUiAction('updateCarRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2 pr-2">申请_{{ticketItem.ticketRequestAt | mdFormat}}</span>
									<span v-if="ticketItem.ticketStatus !== '申请'" @click="doUiAction('viewCarRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2">退车{{ticketItem.ticketStatus}}_{{ticketItem.ticketStatusAt | mdFormat}}</span>
								</div>
							</template>
						</template>
						<template v-slot:item.paid-payment-ticket="{item}">
							<template v-for="(ticketItem, ticketIndex) in item.paymentTicket">
								<div :key="ticketIndex">
									<span @click="doUiAction('updatePaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2 pr-2">申请_{{ticketItem.ticketRequestAt | mdFormat}}</span>
									<span v-if="ticketItem.ticketStatus !== '申请'" @click="doUiAction('viewPaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2">付款{{ticketItem.ticketStatus}}_{{ticketItem.ticketStatusAt | mdFormat}}</span>
								</div>
							</template>
						</template>
						<template v-slot:item.received-payment-ticket="{item}">
							<template v-for="(ticketItem, ticketIndex) in item.receiptTicket">
								<div :key="ticketIndex">
									<span @click="doUiAction('updatePaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2 pr-2">申请_{{ticketItem.ticketRequestAt | mdFormat}}</span>
									<span v-if="ticketItem.ticketStatus !== '申请'" @click="doUiAction('viewPaymentRequest', ticketItem)" role="button" class="success--text font-weight-medium font-size-2">收款{{ticketItem.ticketStatus}}_{{ticketItem.ticketStatusAt | mdFormat}}</span>
								</div>
							</template>
						</template>

	          <template v-slot:item.signingTime="{ item }">{{item.signingTime | dateFormat }}</template>
	          <template v-slot:item.operationAt="{ item }">{{item.operationAt | dateFormat }}</template>
	          <template v-slot:item.contractStartTime="{ item }">{{item.contractStartTime | dateFormat }}</template>
	          <template v-slot:item.contractEndTime="{ item }">{{item.contractEndTime | dateFormat }}</template>
	          <!-- 表格操作按钮 -->
	          <template v-slot:item.action="{ item }">
	            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('startUpdateItem', item)">
	              <v-icon size="16" class="success--text">mdi-note-edit-outline</v-icon>修改
	            </span>
	            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('deleteItem', item)">
	              <v-icon size="16" class="success--text">mdi-trash-can-outline</v-icon>删除
	            </span>
	            <v-menu offset-y>
	              <template v-slot:activator="{ on, attrs }">
	                <span role="button" class="success--text font-weight-medium font-size-2 mr-1"
	                  v-bind="attrs" v-on="on">
	                  操作<v-icon size="14" class="success--text">mdi-chevron-down</v-icon>
	                </span>
	              </template>
	              <v-list dense>
	                <v-list-item v-for="tableButton of tableButtonList" @click="doUiAction(tableButton.action, {...item, ...tableButton})">
	                <v-list-item-title>
	                  {{ tableButton.text }}</v-list-item-title>
	                </v-list-item>
	              </v-list>
	            </v-menu>
	            <!-- <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('startFlowRequest', item)">
	              <v-icon size="16" class="success--text">mdi-credit-card-outline</v-icon>收/付申请
	            </span>
	            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('startDispatchItemCar', item)">
	              <v-icon size="16" class="success--text">mdi-car-back</v-icon>发/退车申请
	            </span>
	            <span role="button" class="success--text font-weight-medium font-size-2 mr-2" @click="doUiAction('toPrintContractView', item)">
	              <v-icon size="16" class="success--text">mdi-printer</v-icon>打印
	            </span>
	          </template>
	          <!-- 没有数据 -->
	          <template v-slot:loading>
	            <div class="jh-no-data">数据加载中</div>
	          </template>
	          <template v-slot:no-data>
	            <div class="jh-no-data">暂无数据</div>
	          </template>
	          <template v-slot:no-results>
	            <div class="jh-no-data">暂无数据</div>
	          </template>
	          <!-- 表格分页 -->
	          <template v-slot:footer.page-text="pagination">
	            <span>{{pagination.pageStart}}-{{pagination.pageStop}}</span>
	            <span class="ml-1">共{{pagination.itemsLength}}条</span>
	          </template>
	          <template v-slot:item.filePath="{ item }">
	            <v-btn  v-if="item.filePath" color="success"  outlined x-small class="elevation-0 mr-2"  @click="filePreview({item})">查看</v-btn>
	            <!-- <a @click="filePreview({item})">{{item.filePath}}</a> -->
	          </template>
	        </v-data-table>
	      </v-card>

	      <!-- 流水申请抽屉 -->
	      <drawer-createTicket ref="createFlowTicket" :ticketType="'flow'"></drawer-createTicket>

	      <!-- 发车/退车申请抽屉 -->
	      <drawer-createTicket ref="createDispatchTicket" :ticketType="'dispatch'" :carId="carId" :carNumber="carNumber"></drawer-createTicket>


	      <!-- 新增合同抽屉 -->
	      <v-navigation-drawer v-if="isCreateDrawerShown" v-model="isCreateDrawerShown" :permanent="isCreateDrawerShown" fixed temporary right width="80%" class="elevation-24">
	        <v-form ref="createForm" lazy-validation>
	          <!-- 抽屉标题 -->
	          <v-row>
	            <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">新增信息</span>
	          </v-row>
	          <!-- 抽屉表单 -->
	          <!-- <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.xxxId" :rules="validationRules.requireRules"></v-text-field> -->
	          <v-row class="mt-0 px-4">
	            <v-col cols="12" sm="12" md="12" xl="12" :class="{'pa-0': isMobile, 'px-3': isMobile, 'pt-6': isMobile}">
	              <span class="inputLabel">合同文件</span>
	              <v-file-input v-model="inputFile" class="jh-v-input mr-2" dense filled single-line chips label="请选择文件" ></v-file-input>
	            </v-col>
	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>车辆编号</span>
	              <v-text-field class="jh-v-input" required readonly dense single-line filled v-model="createItem.carId" label="自动填写" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>
	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>车牌号</span>
	              <v-select class="jh-v-input" dense single-line filled v-model="createItem.carNumber" :items="carBasic" item-text="carNumber" item-value="carNumber" @change="doUiAction('handleCarNumberChange',$event)" :rules="validationRules.requireRules"></v-select>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>客户编号</span>
	              <v-select class="jh-v-input" dense single-line filled v-model="createItem.customerId" :items="customer" item-text="customerName" item-value="customerId" :rules="validationRules.requireRules"></v-select>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>合同开始时间</span>
	              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
	                <template v-slot:activator="{on, attrs}">
	                  <v-text-field v-bind="attrs" v-on="on" v-model="createItem.contractStartTime" class="jh-v-input" dense single-line filled readonly :rules="validationRules.requireRules" label="点击此处选择日期"></v-text-field>
	                </template>
	                <v-date-picker color="success" elevation="20" v-model="createItem.contractStartTime"></v-date-picker>
	              </v-menu>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>合同结束时间</span>
	              <v-menu class="jh-v-input" transition="scale-transition" offset-y min-width="auto">
	                <template v-slot:activator="{on, attrs}">
	                  <v-text-field v-bind="attrs" v-on="on" v-model="createItem.contractEndTime" class="jh-v-input" dense single-line filled readonly :rules="validationRules.requireRules" label="点击此处选择日期"></v-text-field>
	                </template>
	                <v-date-picker color="success" elevation="20" v-model="createItem.contractEndTime"></v-date-picker>
	              </v-menu>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">服务费费率</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.serviceChargeRate"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">服务费总额</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.serviceCharge"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">付款方式</span>
	              <v-select class="jh-v-input" dense single-line filled v-model="createItem.paymentWay" :items="['分期付款','一次付清']"></v-select>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">租金总额</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.rentAmount"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">租赁类型（年租、月租）</span>
	              <v-select class="jh-v-input" dense single-line filled v-model="createItem.leaseType" :items="['年租','月租']"></v-select>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">是否配备司机</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.hasCarDriver" ></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">押金金额</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="createItem.depositAmount"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="6">
	              <span class="jh-input-label">保险条款</span>
	              <v-textarea class="jh-v-input" dense single-line filled v-model="createItem.insuranceClause"></v-textarea>
	            </v-col>

	            <v-col cols="12" sm="12" md="6">
	              <span class="jh-input-label">违约条款</span>
	              <v-textarea class="jh-v-input" dense single-line filled v-model="createItem.breachClause"></v-textarea>
	            </v-col>

	            <v-col cols="12" sm="12" md="6">
	              <span class="jh-input-label">其他费用</span>
	              <v-textarea class="jh-v-input" dense single-line filled v-model="createItem.otherExpenses"></v-textarea>
	            </v-col>

	            <v-col cols="12" sm="12" md="6">
	              <span class="jh-input-label">备注</span>
	              <v-textarea class="jh-v-input" dense single-line filled v-model="createItem.remark"></v-textarea>
	            </v-col>

	          </v-row>

	          <!-- 抽屉操作按钮 -->
	          <v-row class="justify-end mx-0 mt-8 px-6">
	            <v-btn color="success" @click="doUiAction('createItem')" small>保存</v-btn>
	            <v-btn class="elevation-0 ml-2" @click="isCreateDrawerShown = false" small>取消</v-btn>
	          </v-row>
	        </v-form>
	        <!-- 抽屉关闭按钮 -->
	        <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isCreateDrawerShown = false">
	          <v-icon>mdi-close</v-icon>
	        </v-btn>
	      </v-navigation-drawer>


	      <!-- 编辑抽屉 -->
	      <v-navigation-drawer v-if="isUpdateDrawerShown" v-model="isUpdateDrawerShown" :permanent="isUpdateDrawerShown" fixed temporary right width="80%" class="elevation-24">
	        <v-form ref="updateForm" lazy-validation>
	          <!-- 抽屉标题 -->
	          <v-row>
	            <span class="text-subtitle-1 font-weight-medium pa-6 pl-7">修改信息</span>
	          </v-row>
	          <!-- 抽屉表单 -->
	          <v-row class="mt-0 px-4">
	            <!-- <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.xxxId" :rules="validationRules.requireRules"></v-text-field> -->

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">车辆编号</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.carId" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>
	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>车牌号</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.carNumber" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>客户编号</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.customerId" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>合同开始时间</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.contractStartTime" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label"><span class="red--text">*</span>合同结束时间</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.contractEndTime" :rules="validationRules.requireRules"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">服务费费率</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.serviceChargeRate"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">每月支付的服务费</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.serviceCharge"></v-text-field>
	            </v-col>


	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">付款方式（分期付/一次付清）</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.paymentWay"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">租金金额</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.rentAmount"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">租赁类型（年租、月租）</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.leaseType"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">是否配备司机</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.hasCarDriver"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">押金金额</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.depositAmount"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">保险条款</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.insuranceClause"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">违约条款</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.breachClause"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">其他费用</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.otherExpenses"></v-text-field>
	            </v-col>

	            <v-col cols="12" sm="12" md="4">
	              <span class="jh-input-label">备注</span>
	              <v-text-field class="jh-v-input" dense single-line filled v-model="updateItem.remark"></v-text-field>
	            </v-col>

	          </v-row>
	          <!-- 抽屉操作按钮 -->
	          <v-row class="justify-end mx-0 mt-8 px-6">
	            <v-btn color="success" @click="doUiAction('updateItem')" small>保存</v-btn>
	            <v-btn class="elevation-0 ml-2" @click="isUpdateDrawerShown = false" small>取消</v-btn>
	          </v-row>
	        </v-form>
	        <!-- 抽屉关闭按钮 -->
	        <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isUpdateDrawerShown = false">
	          <v-icon>mdi-close</v-icon>
	        </v-btn>
	      </v-navigation-drawer>
	      <!-- <<<<<<<<<<<<< 页面内容 -->

				<carActionRequest-create ref="createCarRequest" @success="doUiAction('getTableData')" />
				<carActionRequest-update ref="updateCarRequest" @success="doUiAction('getTableData')" />
				<carActionRequest-handle ref="handleCarRequest" @success="doUiAction('getTableData')" />

				<paymentRequest-create ref="createPaymentRequest" @success="doUiAction('getTableData')" />
				<paymentRequest-update ref="updatePaymentRequest" @success="doUiAction('getTableData')" />
				<paymentRequest-handle ref="handlePaymentRequest" @success="doUiAction('getTableData')" />

	      <!-- 遮罩层 -->
	      <v-overlay :value="overlay" @click="overlay = false" :opacity="0.85"  style="z-index: 9999;">
	        <v-icon style="position: fixed; right: 30px; top: 30px;" large color="white"
	          @click="overlay = false" :color="fileType === 'pdf' ? '#ccc' : ''">
	          mdi-close-circle
	        </v-icon>
	        <v-icon style="position: fixed; right: 80px; top: 30px;" large color="white"
	          @click="doUiAction('downloadFileByStream', {item: createItem})" :color="fileType === 'pdf' ? '#ccc' : ''">
	          mdi-download
	        </v-icon>
	        <iframe v-if="fileType === 'pdf'" id="pdfPlayer" :src="fileSrc" frameborder="0"
	          style="width: 100vw; height: 100vh; padding: 50px 0 0 0;"></iframe>
	        <v-img v-else max-height="800" max-width="800" :src="fileSrc"></v-img>
	      </v-overlay>
	    </div>

	    <!-- 帮助页抽屉 >>>>>>>>>>>>> -->
	    <v-navigation-drawer v-if="isHelpPageDrawerLoaded" v-model="isHelpPageDrawerShown" :permanent="isHelpPageDrawerShown" fixed temporary right width="80%" class="elevation-24">
	      <iframe style="border: 0" :src="`/${appInfo.appId}/pageDoc#404.md`" width="100%" height="100%"></iframe>
	      <v-btn elevation="0" color="success" fab absolute top left small tile class="drawer-close-float-btn" @click="isHelpPageDrawerShown = false">
	        <v-icon>mdi-close</v-icon>
	      </v-btn>
	    </v-navigation-drawer>
	    <!-- <<<<<<<<<<<<< 帮助页抽屉 -->
		<common-ticketBox ref="commonTicketBox"></common-ticketBox>

	  </v-main>
	</v-app>

	<jh-toast />
	<jh-mask />
	<jh-confirm-dialog />
	</div>
</script>

<div id="app"></div>

{% endblock %}
{% block vueScript %}
{% include 'filter/vueFilters.html' %}
{% include 'common/jianghuJs/fixedTableHeightV4.html' %}
{% include 'component/drawer/drawer-createTicket.html'%}
{% include 'component/ticket/common-ticketBox.html'%}
{% include 'common/constantUtil.html' %}

{% include 'component/ticket/carActionRequest-create.html'%}
{% include 'component/ticket/carActionRequest-update.html'%}
{% include 'component/ticket/carActionRequest-handle.html'%}

{% include 'component/ticket/paymentRequest-create.html'%}
{% include 'component/ticket/paymentRequest-update.html'%}
{% include 'component/ticket/paymentRequest-handle.html'%}


<script type="module">
	new Vue({
		el: "#app",
		template: "#app-template",
		vuetify: new Vuetify(),
		data: () => ({
			tableButtonList: [
				{ text: "发车收款", buttonType: "path", path: "", action: "createPaymentRequest" },
				{ text: "退车付款", buttonType: "path", path: "", action: "createPaymentRequest" },
				{ text: "发车申请", buttonType: "path", path: "", action: "createCarRequest" },
				{ text: "退车申请", buttonType: "path", path: "", action: "createCarRequest" },
				{ text: "打印合同", buttonType: "path", path: "", action: "toPrintContractView" },
				// { text: "测试组件", buttonType: "path", path: "", action: "testTicket" },
			],
			// 签合同
			customer: [],
			carBasic: [],
			// 发车申请
			carId: "",
			carNumber: "",
			dispatchActionData: {},
			// 收付申请
			requestActionData: {},

			// 面包屑
			breadcrumbs: [
				{
					text: "首页",
					disabled: true,
				},
				{
					text: "contractManagement",
					disabled: true,
				},
			],
			isHelpPageDrawerShown: false,
			isHelpPageDrawerLoaded: false,
			isMobile: window.innerWidth < 500,
			// 表格相关数据
			isTableZebraLineShown: true,
			validationRules: {
				requireRules: [v => !!v || "必填"],
			},
			// 下拉选项
			constantObj: {
				leaseType: [
					{ value: null, text: "全部" },
					{ value: "月租", text: "月租" },
					{ value: "年租", text: "年租" },
				],
			},
			serverSearchInput: {
				leaseType: "月租",
			},
			searchInput: null,
			isTableLoading: true,
			tableData: [],
			headers: [
				{
					text: "操作",
					value: "action",
					align: "center",
					sortable: false,
					width: 180,
					class: "fixed",
					cellClass: "fixed",
				},
				{ text: "合同文件", value: "filePath", width: 100 },
				{ text: "合同编号", value: "contractId", width: 120 },
				{ text: "车辆编号", value: "carId", width: 120 },
				{ text: "车牌号", value: "carNumber", width: 120 },
				{ text: "发车申请", value: "get-car-ticket", width: 200 },
				{ text: "退车申请", value: "return-car-ticket", width: 200 },
				{ text: "付款申请", value: "paid-payment-ticket", width: 200 },
				{ text: "收款申请", value: "received-payment-ticket", width: 200 },
				{ text: "客户编号", value: "customerId", width: 120 },
				{ text: "合同开始时间", value: "contractStartTime", width: 120 },
				{ text: "合同结束时间", value: "contractEndTime", width: 120 },
				{ text: "服务费费率", value: "serviceChargeRate", width: 120 },
				{ text: "服务费总额", value: "serviceCharge", width: 120 },
				{ text: "付款方式（分期付/一次付清）", value: "paymentWay", width: 120 },
				{ text: "租金金额", value: "rentAmount", width: 120 },
				{ text: "租赁类型（月租/年租）", value: "leaseType", width: 120 },
				{ text: "是否配备司机", value: "hasCarDriver", width: 120 },
				{ text: "押金金额", value: "depositAmount", width: 120 },
				{ text: "保险条款", value: "insuranceClause", width: 120 },
				{ text: "违约条款", value: "breachClause", width: 120 },
				{ text: "其他费用", value: "otherExpenses", width: 120 },
				{ text: "签约时间", value: "signingTime", width: 120 },
				{ text: "备注", value: "remark", width: 120 },
				{ text: "操作者", value: "operationByUser", width: 120 },
				{ text: "操作时间", value: "operationAt", width: 250 },
			],
			isCreateDrawerShown: false,
			createItem: {},
			createActionData: {},
			isUpdateDrawerShown: false,
			updateItem: {},
			updateItemId: null,
			updateActionData: {},
			deleteItem: {},
			deleteItemId: null,
			// 文件上传
			inputFile: null,
			downloadPrefix: `${window.location.origin}/<$ ctx.app.config.appId $>/upload`,
			overlay: false,
			fileType: "",
			fileSrc: "",
			previewPrefix: `/<$ ctx.app.config.appId $>/upload`,
			// 获取合同Id,删除订单
			contractId: "",

			// 批量
			tableSelected: [],
		}),
		watch: {
			isHelpPageDrawerShown(val) {
				if (val && !this.isHelpPageDrawerLoaded) {
					this.isHelpPageDrawerLoaded = true;
				}
			},
		},
		async created() { },
		mounted() {
			this.doUiAction("getTableData");
			this.doUiAction("getCarBasic");
			this.doUiAction("getCustomer");
		},
		methods: {
			async doUiAction(uiActionId, uiActionData) {
				switch (uiActionId) {
					case 'createPaymentRequest':
						await this.createPaymentRequest(uiActionData);
						break;
					case 'updatePaymentRequest':
						await this.updatePaymentRequest(uiActionData);
						break;
					case 'viewPaymentRequest':
						await this.viewPaymentRequest(uiActionData);
						break;
						
					case 'createCarRequest':
						await this.createCarRequest(uiActionData);
						break;
					case 'updateCarRequest':
						await this.updateCarRequest(uiActionData);
						break;
					case 'viewCarRequest':
						await this.viewCarRequest(uiActionData);
						break;
					case "startPrintContract":
						await this.printContract(uiActionData);
						break;
				
					case "handleCarNumberChange":
						await this.handleCarNumberChange(uiActionData);
						break;
					case "getCustomer":
						await this.getCustomer();
						break;
					case "getCarBasic":
						await this.getCarBasic();
						break;
					case "getTableData":
						await this.getTableData();
						break;
					case "startCreateItem":
						await this.prepareCreateFormData();
						await this.openCreateDrawer();
						break;
					case "createItem":
						await this.prepareCreateValidate();
						await this.confirmCreateItemDialog();
						await this.prepareDoCreateItem();
						await this.doCreateItem();
						await this.closeCreateDrawer();
						await this.getTableData();
						break;
					case "startUpdateItem":
						await this.prepareUpdateFormData(uiActionData);
						await this.openUpdateDrawer();
						break;
					case "updateItem":
						await this.prepareUpdateValidate();
						await this.confirmUpdateItemDialog();
						await this.prepareDoUpdateItem();
						await this.doUpdateItem();
						await this.closeUpdateDrawer();
						await this.getTableData();
						break;
					case "deleteItem":
						await this.prepareDeleteFormData(uiActionData);
						await this.confirmDeleteItemDialog();
						await this.prepareDoDeleteItem();
						await this.doDeleteItem();
						// 同时删除订单记录
						await this.doDeleteOrderItem();
						await this.clearDeleteItem();
						await this.getTableData();
						break;
					case "downloadFileByStream":
						await this.downloadFileByStream(uiActionData);
						break;
					case "toPrintContractView":
						this.toPrintContractView(uiActionData);
						break;
					default:
						console.error("[doUiAction] uiActionId not find", { uiActionId });
						break;
				}
			},
			// ---------- 创建发车申请 doUiAction >>>>>>>>>>>>> ----------
			async createCarRequest(item) {
				
				const orderList = item ? [item] : this.tableSelected;

				if (orderList.length === 0) {
					window.vtoast.fail(`请选择保险订单`);
					throw new Error("请选择保险订单");
				}
				this.isTableLoading = true;
				// const hasApplyTicket = orderList.some(item => item.getCarTicket.some(ticket => ['申请', '处理中'].includes(ticket.ticketStatus)));
				// if (hasApplyTicket) {
				// 	window.vtoast.fail(`还有未完成的申请单`);
				// 	throw new Error("还有未完成的申请单");
				// }

				const orderIds = _.map(orderList, 'contractId');
				await this.$refs.createCarRequest.doUiAction('startCreateItem', {
					orderIds,
					actionType: item.text
				})
				this.isTableLoading = false;
			},
			async updateCarRequest(item) {
				this.$refs.updateCarRequest.doUiAction('startUpdateItem', {
					...item,
					actionType: item.ticketType
				})
			},
			async viewCarRequest(item) {
				this.isTableLoading = true;
				await this.$refs.handleCarRequest.doUiAction('startUpdateItem', {
					ticketIds: [item.ticketId],
					actionType: '查看'
				})
				this.isTableLoading = false;
			},
			// ---------- <<<<<<<<<<<<< 创建发车申请 doUiAction ----------

			// ---------- table selected >>>>>>>>>>>> --------
			tableItemSelected({ item, value }) {
				if (value) {
					this.tableSelected.push(item);
				} else {
					this.tableSelected = _.reject(this.tableSelected, ['contractId', item.contractId]);
				}
			},
			tableToggleSelectAll({ items, value }) {
				if (value) {
					this.tableSelected = items;
				} else {
					this.tableSelected = [];
				}
			},
			// ---------- <<<<<<<<<<< table selected  --------

			// ---------- 付款申请 >>>>>>>>>>>>> ----------
			async createPaymentRequest(item) {
				const orderList = item ? [item] : this.tableSelected;

				if (orderList.length === 0) {
					window.vtoast.fail(`请选择合同订单`);
					throw new Error("请选择合同订单");
				}
				this.isTableLoading = true;
				// const hasApplyTicket = orderList.some(item => item.getCarTicket.some(ticket => ['申请', '处理中'].includes(ticket.ticketStatus)));
				// if (hasApplyTicket) {
				// 	window.vtoast.fail(`还有未完成的申请单`);
				// 	throw new Error("还有未完成的申请单");
				// }

				const orderIds = _.map(orderList, 'contractId');
				await this.$refs.createPaymentRequest.doUiAction('startCreateItem', {
					orderIds,
					actionType: '创建',
					ticketType: item.text
				})
				this.isTableLoading = false
			},
			async updatePaymentRequest(item) {
				this.$refs.updatePaymentRequest.doUiAction('startUpdateItem', {
					...item,
					actionType: '编辑',
					ticketType: item.ticketType
				})
			},
			async viewPaymentRequest(item) {
				this.isTableLoading = true
				await this.$refs.handlePaymentRequest.doUiAction('startUpdateItem', {
					ticketIds: [item.ticketId],
					actionType: '查看'
				})
				this.isTableLoading = false
			},
			// ---------- <<<<<<<<<<<<< 付款申请 ----------
			async printContract(data) {
				window.location.href = `/<$ ctx.app.config.appId $>/printContract`;
			},
			async getCustomer() {
				const rows = (
					await window.jianghuAxios({
						data: {
							appData: {
								pageId: "customerManagement",
								actionId: "selectItemList",
							},
						},
					})
				).data.appData.resultData.rows;
				this.customer = rows;
			},
			async handleCarNumberChange(carNumber) {
				let carObj = this.carBasic.find(item => item.carNumber === carNumber);
				this.createItem.carId = carObj.carId;
			},
			async getCarBasic() {
				const rows = (
					await window.jianghuAxios({
						data: {
							appData: {
								// 该接口调用service方法
								pageId: "basicManagement",
								actionId: "selectItemList",
								where: { operationStatus: "可用" },
								orderBy: [{ column: "operationAt", order: "desc" }],
							},
						},
					})
				).data.appData.resultData.rows;
				this.carBasic = rows;
			},

			async prepareDispatchFormData(uiActionData) {
				this.dispatchActionData = {};
				const { contractId, carNumber, carId } = uiActionData;
				this.carNumber = carNumber;
				this.carId = carId;
				Object.assign(this.dispatchActionData, { contractId });
			},

			async openDispatchDrawer() {
				await this.$refs.createDispatchTicket.doUiAction("open", this.dispatchActionData);
			},

			async prepareFlowRequestFormData(uiActionData) {
				this.requestActionData = {};
				const { contractId } = uiActionData;
				Object.assign(this.requestActionData, { ticketBizId: contractId });
			},

			async openFlowRequestDrawer() {
				await this.$refs.createFlowTicket.doUiAction("open", this.requestActionData);
			},

			/**
			 * 获取表格数据
			 */
			async getTableData() {
				this.isTableLoading = true;
				const backendSearchData = _.pickBy(this.serverSearchInput, (fieldValue, fieldKey) => {
					if (fieldValue !== null && fieldValue !== "") {
						return true;
					}
				});
				const rows = (
					await window.jianghuAxios({
						data: {
							appData: {
								pageId: "contractManagement",
								actionId: "selectItemList",
								actionData: {},
								where: backendSearchData,
								orderBy: [{ column: "operationAt", order: "desc" }],
							},
						},
					})
				).data.appData.resultData.rows;
				this.tableData = rows;
				this.isTableLoading = false;
			},
			// ---------- 新增数据 uiAction >>>>>>>>>> --------
			async prepareCreateFormData() {
				this.createItem = {};
			},

			async openCreateDrawer() {
				this.isCreateDrawerShown = true;
			},

			async prepareCreateValidate() {
				if (await this.$refs.createForm.validate()) {
					return true;
				}
				throw new Error("请完善表单信息");
			},

			async confirmCreateItemDialog() {
				if ((await window.confirmDialog({ title: "新增", content: "确定新增吗？" })) === false) {
					throw new Error("[confirmCreateFormDialog] 否");
				}
			},

			prepareDoCreateItem() {
				const { id, ...data } = this.createItem;
				this.createActionData = data;
			},

			async doCreateItem() {
				await window.vtoast.loading("保存中");
				const fileDesc = this.createItem.fileDesc;
				const file = this.inputFile;
				window.vtoast.loading(`${file.name} 上传进度: 0.00%`);
				// FIXME:此处必须上传合同文件才能新增
				const result = await window.jianghuAxios.httpUploadByStream({
					fileDesc,
					file,
					fileDirectory: "testFile",
					onProgress: (total, loaded) => {
						const progress = Number(((loaded * 100) / total).toFixed(2));
						window.vtoast.loading(`${file.name} 上传进度: ${progress}%`);
						if (loaded === total) {
							window.vtoast.success(`${file.name} 上传进度: 100%`);
						}
					},
				});
				const { status } = result.data;
				const { downloadPath } = result.data.appData.resultData;
				if (status === "success") {
					await window.jianghuAxios({
						data: {
							appData: {
								pageId: "contractManagement",
								actionId: "insertItem",
								actionData: {
									...this.createActionData,
									contractCreateAt: new Date(),
									filePath: downloadPath,
									signingTime: dayjs().format("YYYY-MM-DD hh:mm:ss"),
								},
								idGenerate: {
									type: "idSequence",
									prefix: "HT",
									bizId: "contractId",
									tableName: "contract",
								},
							},
						},
					});
					await window.vtoast.success("新增数据成功");
				} else {
					await window.vtoast.fail("文件上传失败");
				}
			},
			/**
			 * 文件stream下载
			 */
			// TODO::下载未成功时无错误响应
			async downloadFileByStream({ item }) {
				const downloadPath = item.filePath;
				const filename = item.filename || downloadPath.split("/").pop();
				window.vtoast.loading(`${filename} 下载进度: 0%`);
				const buffer = await window.jianghuAxios.httpDownloadByStream({
					downloadPath,
					filename,
					onProgress: (total, loaded) => {
						const progress = Number(((loaded * 100) / total).toFixed(2));
						window.vtoast.loading(`${filename} 下载进度: ${progress}%`);
						if (total === loaded) {
							window.vtoast.success("下载完成");
						}
					},
				});
				window.jianghuAxios.downloadBufferToChrome({ buffer, filename });
			},
			filePreview({ item }) {
				this.editItem = item;
				if (!item.filePath) return;
				const fileType = item.filePath.split(".");
				if (/\.(pdf|PDF)$/.test(item.filePath)) {
					this.fileType = "pdf";
					this.fileSrc =
						"/<$ ctx.app.config.appId $>/public/plugin/pdf/web/viewer.html?file=" +
						encodeURIComponent(this.previewPrefix + item.filePath);
					this.overlay = true;
				}
				if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(item.filePath)) {
					this.fileType = "img";
					this.fileSrc = this.previewPrefix + item.filePath;
				}
				console.log(this.fileSrc);
				this.overlay = true;
			},
			async closeCreateDrawer() {
				this.isCreateDrawerShown = false;
				this.createItem = {};
				this.createActionData = null;
			},
			// ---------- <<<<<<<<<<< 新增数据 uiAction ---------
			// ---------- 修改数据 uiAction >>>>>>>>>>>> --------
			async prepareUpdateFormData(funObj) {
				this.updateItem = _.cloneDeep(funObj);
			},

			async openUpdateDrawer() {
				this.isUpdateDrawerShown = true;
			},

			async prepareUpdateValidate() {
				if (await this.$refs.updateForm.validate()) {
					return true;
				}
				throw new Error("请完善表单信息");
			},

			async confirmUpdateItemDialog() {
				if ((await window.confirmDialog({ title: "修改", content: "确定修改吗？" })) === false) {
					throw new Error("[confirmUpdateItemDialog] 否");
				}
			},

			async prepareDoUpdateItem() {
				const { id, ...data } = this.updateItem;
				this.updateItemId = id;
				this.updateActionData = data;
			},

			async doUpdateItem() {
				await window.jhMask.show();
				await window.vtoast.loading("修改数据");
				await window.jianghuAxios({
					data: {
						appData: {
							pageId: "contractManagement",
							actionId: "updateItem",
							actionData: this.updateActionData,
							where: { id: this.updateItemId },
						},
					},
				});

				await window.jhMask.hide();
				await window.vtoast.success("修改数据成功");
			},

			async closeUpdateDrawer() {
				this.isUpdateDrawerShown = false;
				this.updateItem = {};
				this.updateActionData = null;
				this.updateItemId = null;
			},
			// ---------- <<<<<<<<<<< 修改数据 uiAction ---------
			// ---------- 删除数据 uiAction >>>>>>>>>>>> --------
			async prepareDeleteFormData(funObj) {
				this.deleteItem = _.cloneDeep(funObj);
			},
			async confirmDeleteItemDialog() {
				if ((await window.confirmDialog({ title: "删除", content: "确定删除吗？" })) === false) {
					throw new Error("[confirmDeleteItemDialog] 否");
				}
			},
			async prepareDoDeleteItem() {
				const { id, contractId } = this.deleteItem;
				this.deleteItemId = id;
				// 获取合同id,用于删除订单
				this.contractId = contractId;
			},
			async doDeleteItem() {
				await window.vtoast.loading("删除数据");
				await window.jianghuAxios({
					data: {
						appData: {
							pageId: "contractManagement",
							actionId: "deleteItem",
							actionData: {},
							where: { id: this.deleteItemId },
						},
					},
				});
				await window.vtoast.success("删除数据成功");
			},
			async doDeleteOrderItem() {
				await window.vtoast.loading("删除订单数据");
				await window.jianghuAxios({
					data: {
						appData: {
							pageId: "orderManagement",
							actionId: "deleteItem",
							actionData: {},
							where: { contractId: this.contractId },
						},
					},
				});
				await window.vtoast.success("删除订单成功");
			},
			async clearDeleteItem() {
				this.deleteItem = {};
				this.deleteItemId = null;
			},
			// ---------- <<<<<<<<<<< 删除数据 uiAction ---------
			// 跳转到打印页面
			toPrintContractView({ contractId }) {
				window.open(`/<$ ctx.app.config.appId $>/print/contract/${contractId}`, "_blank");
				// window.location.href = `/<$ ctx.app.config.appId $>/print/contract/${contractId}`;
			},
			testTicket() {
				this.$refs.commonTicketBox.doUiAction('open')
			},

		},
	});
</script>

<style scoped=""></style>
{% endblock %}